//
//  SFRefreshControl.swift
//  SFWeiBo
//
//  Created by 孙凡 on 16/4/14.
//  Copyright © 2016年 Edward. All rights reserved.
//

import UIKit


/**
 三种状态
 1:普通状态
 2:放手就去加载状态,准备状态
 3:加载状态
 */


enum SFRefeshControlType: Int {
    case Normal = 0,Ready = 1,Action = 2
}

class SFRefreshControl: UIControl {
    //自己的高度
    let RefreshHeight: CGFloat = 50

    var scrollView: UIScrollView?

    func endRefresh(){

        if refreshState == .Action {

            print("加载完成,普通状态")
            refreshState = .Normal
        }

    }


    //定义类型
    var refreshState: SFRefeshControlType = .Normal{


        didSet{

            weak var mySelf = self

            switch refreshState {
            case .Ready:
                print("就绪")
                arrowImage.hidden = false
                //修改箭头的transform
                UIView.animateWithDuration(1, animations: { 

                    mySelf!.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "松手发射"


            case .Action:
                print("加载")
                messageLabel.text = "正在加载"
                arrowImage.hidden = true
                indicatorView.startAnimating()

                let insetY: CGFloat = scrollView!.contentInset.top

                UIView.animateWithDuration(0.3, animations: { 

                    mySelf!.scrollView!.contentInset.top = mySelf!.RefreshHeight + insetY
                })


                sendActionsForControlEvents(UIControlEvents.ValueChanged)

            default:
                print("普通状态")
                arrowImage.hidden = false
                UIView.animateWithDuration(1, animations: {

                    mySelf!.arrowImage.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"

                if oldValue == .Action {
                    UIView.animateWithDuration(0.3, animations: { 
                        mySelf!.scrollView?.contentInset.top -= mySelf!.RefreshHeight
                    })
                }
                endRefresh()
            }

        }

    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupUI(){

        backgroundColor = UIColor.blueColor()

        // 添加子控件
        addSubview(arrowImage)
        addSubview(indicatorView)
        addSubview(messageLabel)
        // 添加约束

        arrowImage.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }

        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImage)
        }

        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowImage.snp_trailing)
            make.centerY.equalTo(arrowImage)
        }

        
    }


    //取到父控件
    override func willMoveToSuperview(newSuperview: UIView?) {

        if let scrollView = newSuperview as? UIScrollView {

            self.frame.size = CGSize(width: scrollView.frame.width, height: RefreshHeight)
            self.frame.origin.y = -RefreshHeight
            self.scrollView = scrollView
            //KVO监听scrollView的contentOffset
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)

        }

    }



    //监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        let separateOffsetY = -RefreshHeight - scrollView!.contentInset.top

        let contentOffsetY = scrollView?.contentOffset.y

        //定义三种状态

        //当我在滑动的时候
        if scrollView!.dragging {

            //当scroll的offsetY大于分界线,变为就绪状态
            if contentOffsetY <= separateOffsetY && refreshState == .Normal {

                refreshState = .Ready

            } else if contentOffsetY > separateOffsetY && refreshState == .Ready {

                refreshState = .Normal
            }

        }else if contentOffsetY <= separateOffsetY && refreshState == .Ready{

            refreshState = .Action

        }

    }

    //移除监听
    deinit{

        removeObserver(self.scrollView!, forKeyPath: "contentOffset.y")
    }


    //懒加载控件
    private lazy var indicatorView: UIActivityIndicatorView =  {

        let i = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)

        return i
    }()

    // 箭头
    private lazy var arrowImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "下拉起飞"
        return label
    }()
}
